import { defineStore } from "pinia";
import AliOssSdk from "ali-oss";
import { aliOssSecurityToken } from "@/apis/products/specifications";

const useMultipartOssStore = defineStore("oss", {
  state: () => ({
    clientOssObj: null
  }),
  actions: {
    // 获取STS临时授权
    getAuth() {
      return new Promise(async (resolve, reject) => {
        try {
          const { data } = await aliOssSecurityToken();
          resolve({
            region: "oss-cn-hangzhou",
            bucket: "51-jzt-dev",
            accessKeyId: data.accessKeyId,
            accessKeySecret: data.accessKeySecret,
            stsToken: data.securityToken,
            refreshSTSToken: async () => {
              // 向您搭建的STS服务获取临时访问凭证。
              const { data } = await aliOssSecurityToken();
              return {
                accessKeyId: data.data.accessKeyId, // 自己账户的accessKeyId或临时秘钥
                accessKeySecret: data.data.accessKeySecret, // 自己账户的accessKeySecret或临时秘钥
                stsToken: data.data.securityToken //  从STS服务获取的安全令牌（SecurityToken）。
              };
            },
            // 刷新临时访问凭证的时间间隔，单位为毫秒。
            refreshSTSTokenInterval: 3600 * 1000
          });
        } catch (err) {
          reject(err);
        }
      });
    },
    getClientOss() {
      return new Promise(async (resolve, reject) => {
        try {
          this.clientOss = await this.getAuth();
          this.clientOssObj = new AliOssSdk({
            ...this.clientOss
          });
          resolve(this.clientOssObj);
        } catch (err) {
          reject(err);
        }
      });
    },
    async submit(ObjName, fileData) {
      const client = await this.getClientOss();
      console.log("这是上传操作");
      const options = {
        progress: (p, cpt, res) => {},
        parallel: 4,
        partSize: 1024 * 1024,
        headers: {}
      };
      return await client.multipartUpload(ObjName, fileData, options);
    },
    // 设置文件读写权限
    async setACL(ObjName, configObj) {
      const client = await this.getClientOss();
      return await client.putACL(ObjName, configObj);
    },
    // 获取文件url
    async signatureUrl(ObjName) {
      const client = await this.getClientOss();
      return await client.signatureUrl(`${ObjName}`);
    },
    // 获取上传进度
    async multipartUpload(ObjName, fileData, callback) {
      const client = await this.getClientOss();
      await client.multipartUpload(ObjName, fileData, {
        progress: percent => {
          callback && callback(percent);
        }
      });
    }
  }
});
export default useMultipartOssStore;
